﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
namespace Smokey.Client.Linq {
    public class DBSession : IDisposable {
        private readonly TransactionScope transactionScope;
        private readonly IDbConnection connection;
        private static readonly string connectionString = ConfigurationManager.AppSettings["ConnectionString"];

        private DBSession(TransactionScope transactionScope, IDbConnection connection) {
            this.transactionScope = transactionScope;
            this.connection = connection;
        }

        public IDbConnection Connection {
            get {
                return connection;
            }
        }

        public void CompleteTransaction() {
            transactionScope.Complete();
        }

        protected virtual void Dispose(bool disposing) {
            if (disposing) {
                transactionScope.Dispose();
                connection.Dispose();
                GC.SuppressFinalize(this);
            }
        }

        public void Dispose() {
            Dispose(true);
        }

        public static DBSession CreateDbSession() {
            return CreateDbSession(connectionString);
        }

        public static DBSession CreateDbSession(string connectionString) {
            TransactionScope transactionScope = null;
            IDbConnection connection = null;
            try {
                transactionScope = new TransactionScope();
                connection = new SqlConnection(connectionString);
                connection.Open();

                return new DBSession(transactionScope, connection);
            } catch {
                if (connection != null) {
                    connection.Dispose();
                }

                if (transactionScope != null) {
                    transactionScope.Dispose();
                }

                throw;
            }
        }
    }
}
